import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: import('@/views/login/index.vue')
    },
    {
      path: '/',
      name: 'layout',
      component: () => import('@/views/layout/index.vue'),
      redirect: '/category',
      children: [
        {
          path: 'category',
          component: () => import('@/views/category/index.vue')
        },
        {
          path: 'dish',
          component: () => import('@/views/dish/index.vue')
        },
        {
          path: 'setmeal',
          children: [
            {
              path: '',
              component: () => import('@/views/setmeal/index.vue')
            },
            {
              path: 'addEdit/:id?',
              component: () => import('@/views/setmeal/SetmealAddEdit.vue')
            }
          ]
        },
        {
          path: 'order',
          component: () => import('@/views/order/index.vue')
        },
        {
          path: 'employee',
          component: () => import('@/views/employee/index.vue')
        },
        {
          path: 'user',
          children: [
            {
              path: 'password',
              component: () => import('@/views/user/UserPassword.vue')
            },
            {
              path: 'profile',
              component: () => import('@/views/user/UserProfile.vue')
            }
          ]
        }
      ]
    }
  ]
})

router.beforeEach((to, from, next) => {
  // 原因: router 挂载比 pinia 早, 守卫在使用pinia时，可能因pinia还没有挂载报错，
  // 所以，将以下代码【const userStore = useUserStore()】书写在beforeEach中, 确保pinia已经挂载
  const userStore = useUserStore()
  const token = userStore.token
  if (to.path === '/login') {
    return next()
  }
  // const token = localStorage.getItem("token");
  if (!token) {
    return next('/login')
  }
  next()
})

export default router
